<template>
	<view class="Shell" :style="`padding-top:calc(${wh}px + 88rpx)`">
		<!-- 手机状态栏 -->
		<view :style="'height:' + wh + 'px;' + (scrollb ? 'background-color:white;' : '')" class="topstate"></view>
		<image :src="imgsrc + 'bg_msg.png?v=' + imgVersion" mode="aspectFill" class="topimg"></image>
		<!-- 顶部按钮 -->
		<view class="topnav"
			:style="'top: ' + wh + 'px;background-color: ' + (scrollb ? 'white' : '') + ';margin-top:' + (biasTop) + 'px;'+(capsule?'padding-right:212rpx':'')">
			<view class="t-left">
				<text class="tl-text">消息</text>
				<view class="tl-mark" @tap.stop.prevent="readAllFn">
					<view>
						<image :src="imgsrc + 'clear_msg.png?v=' + imgVersion" mode="aspectFill"></image>
					</view>
					全部已读
				</view>
			</view>
			<view class="t-right">
				<navigator style="margin-right: 43rpx" open-type="navigate"
					:url="'/pages/redirect/index?url=' + encodeURIComponent(friendlist)" hover-class="none">
					<image :src="imgsrc + 'friend_list.png?v=' + imgVersion" mode="aspectFill"></image>
				</navigator>
				<navigator open-type="navigate" :url="'/pages/redirect/index?url=' + encodeURIComponent(addfriend)"
					hover-class="none">
					<image :src="imgsrc + 'add_friend.png?v=' + imgVersion" mode="aspectFill"></image>
				</navigator>
			</view>
		</view>
		<view class="topbtn">
			<!-- 赞 -->
			<navigator class="t-support" open-type="navigate"
				:url="'/pages/redirect/index?url=' + encodeURIComponent(zanurl)" hover-class="none">
				<view class="ts-icon">
					<image :src="imgsrc + 'zan_icon.png?v=' + imgVersion" mode="aspectFill"></image>
					<view class="tsi-num" v-if="numdata.upunread">{{ numdata.upunread }}</view>
				</view>
				<text>赞</text>
			</navigator>
			<!-- 评论 -->
			<navigator class="t-comment" open-type="navigate"
				:url="'/pages/redirect/index?url=' + encodeURIComponent(commenturl)" hover-class="none">
				<view class="ts-icon">
					<image :src="imgsrc + 'cmmt_icon.png?v=' + imgVersion" mode="aspectFill"></image>
					<view class="tsi-num" v-if="numdata.commentunread">{{ numdata.commentunread }}</view>
				</view>
				<text>评论</text>
			</navigator>
			<!-- 粉丝 -->
			<navigator class="t-fans" open-type="navigate"
				:url="'/pages/redirect/index?url=' + encodeURIComponent(fansurl)" hover-class="none">
				<view class="ts-icon">
					<image :src="imgsrc + 'fans_icon.png?v=' + imgVersion" mode="aspectFill"></image>
				</view>
				<text>粉丝</text>
			</navigator>
		</view>
		<!-- 通知消息 -->
		<view class="system">
			<navigator class="s-system" open-type="navigate" url="/pages/member/systemMsg/index" hover-class="none"
				v-if="systemdata.id" @touchstart.capture="touchFn" @touchend.capture="touchEfn"
				:style="'background-color: ' + (sysb ? '#F7F7F7' : '') + ';'">
				<view style="position: relative; width: 98rpx; height: 98rpx; margin-right: 24rpx; border-radius: 50%">
					<image :src="imgsrc + 'system_msg.png?v=' + imgVersion" mode="aspectFill"></image>
					<view class="si-num" v-if="systemunred">{{ systemunred }}</view>
				</view>
				<view class="ss-content">
					<text class="title">系统通知</text>
					<view>{{ systemdata.title }}</view>
				</view>
				<view class="ss-time">{{ systemdata.date }}</view>
			</navigator>
			<scroll-view style="overflow: hidden; width: 100%" v-for="(item, index) in listdata" :key="index" scroll-x
				@touchstart="touchStartFn" @touchend="touchEndFn" :scroll-left="touchIndex == index?moveX:0"
				scroll-with-animation :data-index="index" @scroll="checkDragFn" :show-scrollbar="false"
				:enhanced="true">
				<navigator class="s-item" open-type="navigate" hover-class="none"
					:style="index == touchIndex ? 'background-color:#F7F7F7;' : 'background-color:white;'"
					:url="'/pages/redirect/index?url=' + encodeURIComponent(item.url)">
					<view
						style="position: relative; width: 98rpx; height: 98rpx; margin-right: 24rpx; border-radius: 50%; flex-shrink: 0;">
						<image :src="item.userinfo.photo" mode="aspectFill" @error="errorFn" :data-index="index">
						</image>
						<view class="si-num" v-if="item.unread">{{ item.unread }}</view>
					</view>

					<view class="ss-content">
						<text class="title">{{ item.userinfo.name }}</text>
						<view class="msgView">{{ item.lastMessage.type == 'link' || item.lastMessage.type == 'enquiryDetail' ? '[链接消息]' : item.lastMessage.content }}</view>
					</view>

					<view class="ss-time">{{ item.lastMessageTime }}</view>

					<view class="ss-delete" @tap.stop.prevent="deleteFn" :data-tid="item.userinfo.uid"
						:data-index="index">
						<image :src="imgsrc + 'del_btn.png?v=' + imgVersion" mode="aspectFill"></image>
					</view>
				</navigator>
			</scroll-view>
		</view>
		<!-- 无数据 -->
		<view class="nondatas" :style="'display: ' + (datab ? 'block' : 'none') + ';'">
			<image :src="imgsrc + 'noMsg.png?v=' + imgVersion" mode="aspectFill"></image>
			<view>在这里你可以收发消息哦~</view>
		</view>
		<!-- 删除弹窗 -->
		<view class="pop" :style="'display: ' + (deleteb ? 'block' : 'none') + ';'">
			<view class="p-content">
				<view class="pc-title">确认删除消息？</view>
				<view class="pc-btn">
					<view class="pcb-cancel" @tap.stop.prevent="cancelFn">取消</view>
					<view class="pcb-clear" @tap.stop.prevent="confirmFn">确认</view>
				</view>
			</view>
		</view>
		<!-- 弹框提醒 -->
		<view class="pop-warning" :style="'transform:scale(' + (warningb ? '1' : '0') + ');'">
			<view class="text" style="transform: translate(-50%, -50%)">{{ info }}</view>
		</view>
		<bottom :module="modules" active="message" :total="numdata.total > 99 ? '99+' : numdata.total"
			:needCity="false">
		</bottom>
		<private_tip :privateShow="privateb"></private_tip>
	</view>
</template>

<script>
	import bottom from '../../../components/bottom_nav/bottom_nav';
	// pages/member/message/message.js
	let app = getApp();
	var timer;
	var _this;
	let timerArr = [];
	export default {
		components: {
			bottom
		},
		data() {
			return {
				// 高/宽度(px)
				wh: app.globalData.navTop,
				biasTop: 0,
				privateb: false,
				// 域名
				imgsrc: `${app.globalData.masterDomain}/templates/member/touch/im/images/`,

				staticimg: `${app.globalData.masterDomain}/static/images/`,
				appConfig: app.globalData.appConfig,
				// 接口数据
				listdata: '',
				addUrlParam: app.addUrlParam,
				numdata: {
					upunread: '',
					commentunread: '',
					total: 0
				},

				systemdata: {
					id: '',
					title: '',
					date: ''
				},

				// 移动距离
				startX: 0,
				moveX: 0,
				// 布尔变量
				datab: false,
				deleteb: false,
				warningb: false,
				firstb: false,
				scrollb: false,
				sysb: false,

				// url地址
				zanurl: '',

				commenturl: '',
				fansurl: '',
				friendlist: '',
				addfriend: '',

				// 自定义数据
				touchIndex: -1,

				tid: '',
				systemunred: 0,
				modules: 'siteConfig',
				info: '',
				imgVersion: '',
				delIndex: -1,
				// 兼容项
				capsule: false,
				timerMsg:null,
			};
		},
		onPageScroll(e) {
			//触顶
			_this.scrollb = e.scrollTop <= 0 ? false : true
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			_this = this;
			// app.watch(this.pageChangeVisible,'pageVisible') undefined报错
			if (app.globalData.wxprivate == -1) {
				app.watchG('wxprivate', function(value) {
					_this.wxprivate=value;
					if (value) { //弹出弹窗
						_this.privateb = true;
					} else {
						_this.onload(options);
					}
				})
			} else {
				if (app.globalData.wxprivate) { //弹出弹窗
					_this.privateb = true;
				} else {
					_this.onload(options);
				}
			}
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			clearInterval(this.timerMsg)
			this.timerMsg = setInterval(res => {
				if (!this.firstb) { //首次进入不执行
					this.getData();
					console.log('重新获取数据');
				}
			}, 5000);
			this.firstb = false;
			this.pageShowCheck(5)	
			
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {
			for (let i = 0; i < timerArr.length; i++) {
				//清除定时器，防止叠加卡死
				clearInterval(timerArr[i]);
			}
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			for (let i = 0; i < timerArr.length; i++) {
				//清除定时器，防止叠加卡死
				clearInterval(timerArr[i]);
			}
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			app.reloadFn();
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage(res) {
			let config = app.globalData.appConfig;
			return {
				title: config.share.title,
				desc: config.share.description,
				path: `/pages/${dyConfig.template}/index`,
				imageUrl: app.globalData.masterDomain + '/include/json.php?action=getSystemLogo'
			};
		},
		onShareTimeline() {
			return {
				title: config.share.title,
				imageUrl: app.globalData.masterDomain + '/include/json.php?action=getSystemLogo'
			};
		},
		methods: {
			onload(options) {
				// 平台切换
				let platForm = app.globalData.platForm;
				if (platForm == 'mp-toutiao') { //抖音
					this.capsule = false; //胶囊是否显示/隐藏
				} else if (platForm == 'mp-weixin') { //微信
					if (Boolean(app.globalData.biasTop_88)) {
						this.biasTop = app.globalData.biasTop_88 //顶部偏差
					} else {
						app.biasTop('.topnav', _this)
					}
					this.capsule = true;
				}
				//数据加载
				if (options.access_token && options.refresh_token) {
					app.globalData.userid = options.userid
					uni.setStorage({
						key: 'access_token',
						data: options.access_token
					});
					uni.setStorage({
						key: 'refresh_token',
						data: options.refresh_token
					});
					var token_expired = Date.parse(new Date()) / 1000 + 7200 -
						20; //两个小时有效期，保险起见，用1小时59分钟40秒
					uni.setStorage({
						key: 'token_expired',
						data: token_expired
					});
					uni.setStorage({
						key: 'userid',
						data: options.userid,
					})
				}
				uni.showLoading({
					title: '加载中'
				});
				if (options.module != '' && options.module != undefined) {
					_this.modules = options.module
				}
				_this.getData();
				let userid = app.globalData.userid;
				let cfg_user_index = app.globalData.appConfig.cfg_user_index;
				// 粉丝url
				let zanurl = `${cfg_user_index}/im/commt_list.html`;
				let commenturl = `${cfg_user_index}/im/commt_list.html`;
				let fansurl = `${cfg_user_index}/user/${userid}/fans.html`;
				let friendlist = `${cfg_user_index}/im/f_list.html`;
				let addfriend = `${cfg_user_index}/im/search_list.html`;
				_this.zanurl = encodeURIComponent(app.addUrlParam(
					zanurl)) + '#zan';
				_this.commenturl = encodeURIComponent(app.addUrlParam(
					commenturl)) + '#commt';
				_this.fansurl = encodeURIComponent(app.addUrlParam(
					fansurl));
				_this.friendlist = encodeURIComponent(app.addUrlParam(
					friendlist));
				_this.addfriend = encodeURIComponent(app.addUrlParam(
					addfriend));
			},
			getData() {
				_this.$ajax.post({
					url: `include/ajax.php?${app.encodeUrl('service=member&action=message')}`,
					data: {
						type: 'tongji',
						im: 1
					},
				}).then(res => {
					if (res.data.state == 100) {
						_this.numdata = res.data.info.pageInfo
					}
				})
				// 系统通知数据
				_this.$ajax.post({
					url: `include/ajax.php?${app.encodeUrl('service=member&action=message')}`,
					data: {
						page: 1,
						pageSize: 1
					},
				}).then(res => {
					if (res.data.state == 100) {
						let timestamp = res.data.info.list[0].timestamp;
						let date = +new Date() / 1000;
						let time = date - timestamp;
						let data = this.timestampToTime(timestamp);
						if (time < 60) {
							//小于一分钟
							res.data.info.list[0].date = '刚刚';
						} else if (time < 86400) {
							//小于一天
							res.data.info.list[0].date = `${data.hour}:${data.minutes}`;
						} else if (time < 172800) {
							//小于两天
							res.data.info.list[0].date = `昨天 ${data.hour}:${data.minutes}`;
						} else if (time < 31536000) {
							//小于一年
							res.data.info.list[0].date = `${data.month}/${data.day}`;
						} else {
							//大于一年
							res.data.info.list[0].date = `${data.year}/${data.month}/${data.day}`;
						}
						_this.systemdata = res.data.info.list[0];
						_this.systemunred = res.data.info.pageInfo.unread
					} else {
						_this.systemdata = []
						_this.systemunred = 0
					}
					uni.hideLoading();
				})
				let userid = app.globalData.userid;
				// 列表数据
				if(!userid) return false
				_this.$ajax.post({
					url: `include/ajax.php?${app.encodeUrl('service=siteConfig&action=getImFriendList')}`,
					data: {
						userid: userid,
						type: 'temp'
					},
				}).then(res => {
					if (res.data.state == 100) {
						let cfg_user_index = app.globalData.appConfig.cfg_user_index;
						if (res.data.info.length == 0) {
							_this.datab = true
						}
						let date = +new Date() / 1000;
						for (let i = 0; i < res.data.info.length; i++) {
							// url地址修改
							let url =
								`${cfg_user_index}/im/chat-${res.data.info[i].userinfo.uid}.html`;
							res.data.info[i].url = encodeURIComponent(app.addUrlParam(
								url));
							// 时间格式修改
							let time = date - res.data.info[i].lastMessageTime;
							let data = this.timestampToTime(res.data.info[i]
								.lastMessageTime);
							if (time < 60) {
								//小于一分钟
								res.data.info[i].lastMessageTime = '刚刚';
								continue;
							} else if (time < 86400) {
								//小于一天
								res.data.info[i].lastMessageTime =
									`${data.hour}:${data.minutes}`;
								continue;
							} else if (time < 172800) {
								//小于两天
								res.data.info[i].lastMessageTime =
									`昨天 ${data.hour}:${data.minutes}`;
								continue;
							} else if (time < 31536000) {
								//小于一年
								res.data.info[i].lastMessageTime =
									`${data.month}/${data.day}`;
								continue;
							} else {
								//大于一年
								res.data.info[i].lastMessageTime =
									`${data.year}/${data.month}/${data.day}`;
							}
						}
						_this.listdata = res.data.info;
					}
					uni.hideLoading();
				})
			},
			touchFn() {
				_this.sysb = true
			},

			touchEfn() {
				_this.sysb = false
			},

			touchStartFn(e) {
				let index = e.currentTarget.dataset.index;
				_this.startX = e.touches[0].clientX;
				if (_this.touchIndex != index) { //选择其他的项偏移量置为0
					_this.moveX = 0;
				}
				_this.touchIndex = index;
			},
			checkDragFn(e) {
				let scrollLeft = e.detail.scrollLeft;
				if (scrollLeft > 80) {
					_this.moveX = 80 + 0.0000000001 //改变偏移量的值使其重新定位
				} else if (scrollLeft < 0) {
					_this.moveX = 0.1 - 0.0000000001
				}
			},
			touchEndFn(e) {
				let endX = e.changedTouches[0].clientX;
				if (endX - (_this.startX) < -60) {
					_this.moveX = 80
				} else {
					_this.moveX = 0.0001 //初始值的偏移量是0，故这里不能为0
					_this.touchIndex = -1
				}
			},

			timestampToTime(timestamp) {
				//时间选择专享
				// let date = new Date(timestamp * 1000); //时间戳为秒需*1000，时间戳为毫秒的话不需乘1000
				
				const dateFormatter = app.dateFormatter(timestamp);
				const Y = dateFormatter.year;
				const M = dateFormatter.month ;
				const D = dateFormatter.day;
				const h = dateFormatter.hour;
				const m = dateFormatter.minute;
				const s = dateFormatter.second;
				let time = {
					year: Y,
					month: M,
					day: D,
					hour: h,
					minutes: m,
					seconds: s
				};
				return time;
			},

			// 头像加载失败
			errorFn(e) {
				let index = e.currentTarget.dataset.index;
				let listdata = this.listdata;
				listdata[index].userinfo.photo = `${this.staticimg}/noPhoto_60.jpg`;
				_this.listdata = listdata
			},

			// 删除单条信息
			deleteFn(e) {
				let tid = e.currentTarget.dataset.tid;
				let index = e.currentTarget.dataset.index
				_this.delIndex = index;
				_this.deleteb = true;
				_this.tid = tid;
			},

			// 取消删除
			cancelFn() {
				_this.deleteb = false
			},

			// 确认删除
			confirmFn() {
				uni.showLoading({
					title: '加载中',
					success: res => {
						_this.$ajax.post({
							url: `include/ajax.php?${app.encodeUrl('service=siteConfig&action=delFriend')}`,
							data: {
								tid: this.tid,
								type: 'temp'
							},
						}).then(res => {
							_this.listdata.splice(_this.delIndex, _this.delIndex + 1);
							_this.deleteb = false;
							this.warnFn(res.data.info);
							uni.hideLoading();
						})
					}
				});
			},

			warnFn(info) {
				clearTimeout(timer);
				_this.warningb = true
				_this.info = info
				timer = setTimeout(() => {
					_this.warningb = false
				}, 2000);
			},

			// 全部已读
			readAllFn() {
				if (this.numdata.total == 0) {
					this.warnFn('暂无未读消息');
					return false
				} else {
					this.numdata.upunread = 0;
					this.numdata.commentunread = 0;
					this.numdata.total = 0;
					this.systemunred = 0;
					for (let i = 0; i < this.listdata.length; i++) {
						let item = this.listdata[i];
						item.unread = 0;
					}
					this.warnFn('操作成功');
					_this.$ajax.post({
						url: `include/ajax.php?${app.encodeUrl('service=member&action=readAllMessage')}`,
					})
				}
			},

			pageShowCheck(timeOut){ // timeOut => 单位是分钟 一段时间过后 修改定时器  interval请求时间间隔 单位是秒
				const that = this;
				let next_timeOut = timeOut;
				let interval = 5
				switch(timeOut){
					case 5: 
						next_timeOut = 10,
						interval = 10;
						break;
					case 10: 
						next_timeOut = 20,
						interval = 20;
						break;
					case 20: 
						next_timeOut = 30,
						interval = 30;
						break;
					case 30: 
						next_timeOut = 60,
						interval = 60;
						break;
					case 60: 
						next_timeOut = 0,
						interval = 0;
						break;
				}
				setTimeout(() => {
					clearInterval(that.timeMsg)
					if(timeOut && interval){
						that.timeMsg = setInterval(this.getData,interval * 1000)
					}
					if(next_timeOut){
						that.pageShowCheck(next_timeOut)
					}
				},timeOut * 60 * 1000);
			}
		},

		// 页面切换至前后台之后触发
		pageChangeVisible(val){
			// 未知原因 不能监听
			if(val){ //表示显示在前台
				clearInterval(this.timeMsg)
				this.timeMsg = setInterval(res => {
					this.getData();
				}, 5000)
				this.pageShowCheck(5)
			}else{ //表示切换至后台
				clearInterval(this.timeMsg)
			}	
		},
	};
</script>
<style>
	@import './index.css';
</style>